<template>
  <section class='f-login' :style="{'height': currentHeight + 'px'}">
    <img class="f-login_bg" src="@/assets/imgs/login_bg_pic.png" alt="">
    <p class="f-login-name">欢迎使用智享App</p>

    <van-form ref="ruleFormRef" class="f-form">
      <ul class="f-login-type">
        <li :class="{'f-select-li': loginType == 1}" @click="loginType = 1">密码登录</li>
        <li :class="{'f-select-li': loginType == 2}" @click="loginType = 2">验证码登录</li>
      </ul>

      <van-cell-group inset style="background-color: transparent;">
        <van-field v-model="form.account" clearable name="account" type="number" placeholder="请输入手机号码" maxlength="11"
          :rules="[{ required: true, message: '请输入手机号码' }]">
          <template #left-icon>
            <p class="f-mr-10">手机号码</p>
          </template>
        </van-field>

        <van-field v-show="loginType == 1" class="f-mt-30" v-model="form.password" :type="form.showPassword?'':'password'"
          clearable name="password" placeholder="请输入登录密码" style="border-bottom:1px solid red"
          :rules="[{ required: true, message: '请输入登录密码' }]">
          <template #left-icon>
            <p class="f-mr-10">登录密码</p>
          </template>
          <template #right-icon>
            <van-icon v-show="!form.showPassword" name="closed-eye" style="width:14px" @click="form.showPassword = true" />
            <van-icon v-show="form.showPassword" name="eye-o" style="width:14px" @click="form.showPassword = false" />
          </template>
        </van-field>

        <van-field v-show="loginType == 2" class="f-mt-30" v-model="form.verificationCode" clearable name="verificationCode"
          placeholder="请输入验证码" maxlength="6" :rules="[{ required: true, message: '请输入验证码' }]">
          <template #left-icon>
            <p class="f-mr-10">验证码</p>
          </template>
          <template #extra>
            <div class="f-ml-10" style="font-size: 14px;color: #3967D9;" @click="getMsgCodeHandle">{{count? count + '秒': '获取验证码'}}
            </div>
          </template>
        </van-field>

        <van-field v-show="false" />
      </van-cell-group>

      <section v-show="loginType == 1" class="f-flex-between f-mt-10" style="font-size: 12px;color: #424242;padding: 10px 32px">
        <van-checkbox v-model="keepPWD" shape="square" icon-size="15px" checked-color="#337ACC">记住密码</van-checkbox>
        <p @click="toForget">忘记密码？</p>
      </section>

      <div class="f-submit-btn">
        <van-button round block type="primary" color="#337ACC" native-type="submit" @click="onSubmit">
          登录
        </van-button>
      </div>

      <div class="f-register" @click="toRegister">
        <p>新用户？</p>
        <p style="color:#337ACC">去注册</p>
      </div>
    </van-form>

    <section class="f-bottom">
      <van-checkbox v-model="checked" checked-color="#3366FF" icon-size="15px">我已阅读并同意
        <span class="link-box" @click.stop="lookxieyi(0)">《用户协议》</span>和
        <span class="link-box" @click.stop="lookxieyi(1)">《隐私政策》</span>
      </van-checkbox>
    </section>

    <xieyi-pop ref="xieyiPopRef" />
  </section>
</template>
<script>
import { ref, reactive, toRefs, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router'
import { useStore } from "vuex";
import { showConfirmDialog } from 'vant';
import { removeStore, getStore, successDeal, setStore } from '@/utils/utils';
import api from './api'
import xieyiPop from '@/components/xieyiPop.vue'
import hexMD5 from "@/utils/md5.min.js"
import JsBridge from '@/utils/JsBridge.js'

export default {
  components: {
    xieyiPop,
  },
  setup(props, context) {
    const store = useStore()

    const router = useRouter()
    const route = useRoute();

    const xieyiPopRef = ref(null)
    const ruleFormRef = ref(null)

    const state = reactive({
      form: {
        account: '',
        password: '',
      },

      keepPWD: false,
      checked: true,
      currentHeight: '',

      loginType: 1,
      counter: 0, // 计时器
      count: 0,

      isAndroid: navigator.userAgent.indexOf('Android') > -1 || navigator.userAgent.indexOf('Adr') > -1,
      isiOS: !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/),
    })

    onMounted(() => {
      let userAccont = getStore('USER_ACCONT')
      if (userAccont) {
        state.keepPWD = true
        state.form.account = userAccont.account
        state.form.password = userAccont.password
      }

      state.currentHeight = window.innerHeight
    })

    const onSubmit = async (values) => {
      if (!state.checked) {
        await showConfirmDialog({
          title: '用户使用协议',
          message: '我已阅读并同意《用户使用协议》',
          confirmButtonText: '同意',
          cancelButtonText: '拒绝',
        }).then(() => {
          state.checked = true
        }).catch(() => {
          return
        })
      }

      if (!state.checked) {
        // warningDeal('请同意用户使用协议')
        return
      }

      if (state.loginType == 1) {
        let json = {
          "account": state.form.account,
          "password": hexMD5(state.form.password),
          noAuthorization: true
        }

        api.login(json).then(res => {
          setStore('USER_INFO', res.data)
          setRemoveStore()
          if (state.keepPWD) {
            setStore("USER_ACCONT", {
              "account": state.form.account,
              "password": state.form.password
            });
          } else {
            removeStore('USER_ACCONT')
          }
          router.replace('/home')
        })
      } else {
        let json = {
          "account": state.form.account,
          "source": state.isAndroid ? "android" : 'ios',
          "verificationCode": state.form.verificationCode
        }
        api.loginSms(json).then(res => {
          setStore('USER_INFO', res.data)
          setRemoveStore()
          router.replace('/home')
        })
      }
    };

    const setRemoveStore = () => {
      removeStore('cards')
      removeStore('cardInfo')
      removeStore('packcardInfo')
      removeStore('CURRENT_CODE')
    }

    const toForget = () => {
      router.push({
        path: '/forget'
      })
    }

    const toRegister = () => {
      router.push({
        path: '/register'
      })
    }

    const toRealName = async (shopUserPhone) => {
      const re = await router.push({
        path: '/realName',
        query: {
          shopUserPhone
        }
      })
    }

    function lookxieyi(type) {
      xieyiPopRef.value.dialogShow(type)
    }

    // 获取短信验证码
    const getMsgCodeHandle = () => {
      if (state.count) return
      ruleFormRef.value.validate(['account']).then(res => {
        state.count = 120;
        countDown();

        let json = {
          phone: state.form.account,
          "source": state.isAndroid ? "android" : 'ios', // android, ios, pc, wxxcx
          smsWay: 'login', // forget|login|modify|register
        }
        api.getSmsCode(json).then((res) => {
          successDeal('短信已发送！')
        }).catch(err => {
          state.count = 0
          clearCounter()
        })
      })
    }

    //计时
    const countDown = () => {
      let count = state.count;

      clearCounter();
      state.counter = setInterval(() => {
        count--;
        state.count = count;
        if (count == 0) {
          clearCounter();
        }
      }, 1000);
    }

    //清除定时器
    const clearCounter = () => {
      clearInterval(state.counter);
    }

    return {
      ...toRefs(state),
      ruleFormRef,
      xieyiPopRef,
      onSubmit,
      toForget,
      toRegister,
      lookxieyi,
      getMsgCodeHandle,
    }
  }
}
</script>
<style lang='scss' scoped>
.f-login {
  position: relative;
  overflow: hidden;
  .f-login_bg {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    z-index: -1;
  }
  .f-login-name {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 93px;
    left: 27px;
    font-weight: 500;
    font-size: 24px;
    color: #ffffff;
  }
  .f-form {
    background: #ffffff;
    border-radius: 27px 27px 0 0;
    position: absolute;
    width: 100%;
    height: 100%;
    top: 177px;
    .f-name {
      padding-top: 30px;
      padding-bottom: 5px;
      font-weight: 550;
      font-size: 16px;
      color: #000000;
      margin-left: 15px;
    }
    .f-login-type {
      font-weight: 400;
      font-size: 16px;
      color: #666666;
      display: flex;
      align-items: center;
      justify-content: space-around;
      margin-top: 32px;
      margin-bottom: 32px;
      li {
        width: 134px;
        text-align: center;
        padding-bottom: 14px;
        border-bottom: 1px solid #fff;
      }
      .f-select-li {
        color: #000000;
        border-bottom: 1px solid #3967d9;
      }
    }
  }
  .f-submit-btn {
    margin-top: 70px;
    padding: 0 60px;
  }
  .f-img {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    z-index: -1;
  }
  .f-bottom {
    position: absolute;
    bottom: 20px;
    left: 0px;
    width: 100%;
    display: flex;
    justify-content: center;
    font-size: 13px;
    color: #424242;
    .van-checkbox__icon--round .van-icon {
      border-color: #424242;
    }
    .van-checkbox__icon--checked .van-icon {
      border-color: var(--van-checkbox-checked-icon-color);
    }
  }
  .f-to-register {
    text-align: center;
    font-size: 16px;
    margin-top: 127px;
  }

  .van-cell {
    background-color: transparent;
  }
  .link-box {
    text-decoration: underline;
    color: #3366ff;
  }
  .f-register {
    display: flex;
    justify-content: center;
    margin-top: 20px;
    color: gray;
  }
}
</style>